import 'package:fijkplayer/fijkplayer.dart';
import 'package:flutter/material.dart';
import 'package:videopiclist/utils.dart';

import 'beans/VideoItem.dart';

void main() {
  runApp(
    MaterialApp(
      home: MyApp(),
    ),
  );
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<VideoItem> list = [];
  List<FijkPlayer> players = [];

  @override
  void initState() {
    super.initState();
    for(var i=0;i<10;i++){
      list.addAll(Utils.getData());
    }
    // list = Utils.getData();
    for (var item in list) {
      players.add(FijkPlayer());
    }
  }

  @override
  void dispose() {
    super.dispose();
   players.forEach((element) {
     element.release();
   });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("视频与图片混合列表"),
      ),
      body: Container(
          child: ListView.builder(
              itemCount: list.length,
              itemBuilder: (BuildContext context, int position) {
                // List items = dataNet["data"];
                var item = list[position];
                return Container(
                  height: MediaQuery.of(context).size.height / 2,
                  child: Column(
                    children: [
                      Text("$position-" + item.title),
                      getVideoOrPic(list, position),
                    ],
                  ),
                );
              })),
    );
  }

  getVideoOrPic(List<VideoItem> list, int position) {
    var item = list[position];
    print("item--$item");
    if (item.type == "video") {
      players.forEach((element) {
        if(element.value.state == FijkState.started){
          element.pause();
        }
      });
      if (item.isPlay) {
        players[position].setDataSource(item.url, autoPlay: true);
        players[position].start();
        return Container(
          child: FijkView(
            player: players[position],
            height: MediaQuery.of(context).size.height / 2 - 50,
          ),
        );
      } else {
        return GestureDetector(
          child: Image.network(item.icon),
          onTap: () {
            setState(() {
              for (int i = 0; i < list.length; i++) {
                if (i == position) {
                  list[i].isPlay = true;
                } else {
                  list[i].isPlay = false;
                }
              }
            });
          },
        );
      }
    } else {
      return Image.network(
        item.url,
        height: MediaQuery.of(context).size.height / 2 - 50,
      );
    }
  }
}
